package com.kuang.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.kuang.pojo.User;
import com.kuang.util.JsonUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.SimpleFormatter;


//@Controller  走视图解析器
@RestController//下面的所有方法只会返回一个json字符串  走字符串
public class UserController {

    @RequestMapping(value = "/j1")
    //@RequestMapping(value = "/j1" ,produces = "application/json;charset=utf-8")太麻烦不推荐使用
    @ResponseBody //他就不会走视图解析器 , 会直接返回一个字符串 //配合 @Controller  使用 ,如果不用@Controller 而是用@RestController 择他没有用处
    public String json1() throws JsonProcessingException {

        //jackson  ObjectMapper
        ObjectMapper mapper = new ObjectMapper();

        //创建一个对象
        User user = new User("男","张立帅",24);

        String str = mapper.writeValueAsString(user);

        return  str;
    }

    @RequestMapping(value = "/j2")
     public String json2() throws JsonProcessingException {

        List<User> userList = new ArrayList<User>();

        User user = new User("男","张立帅",24);
        User user1 = new User("男","张立帅2",24);
        User user2 = new User("男","张立帅3",24);
        User user3 = new User("男","张立帅4",24);

        userList.add(user);
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);

        return  JsonUtils.getJson(userList);
    }

    @RequestMapping(value = "/j3")
    public String json3() throws JsonProcessingException {

        Date date = new Date();

        return JsonUtils.getJson(date);
    }

    @RequestMapping(value = "/j4")
    public String json4() throws JsonProcessingException {

        List<User> userList = new ArrayList<User>();

        User user = new User("男","张立帅",24);
        User user1 = new User("男","张立帅2",24);
        User user2 = new User("男","张立帅3",24);
        User user3 = new User("男","张立帅4",24);

        userList.add(user);
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);

        String s = JSON.toJSONString(userList);
        return s;
    }

}
